package com.iseastar.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.iseastar.guojiang.register.RegisterCourierStepActivity;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.iseastar.guojiang.view.DeleteEditText;
import com.shouhuobao.station.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import droid.frame.utils.lang.Str;

/**
 * 火箭侠注册
 * Created by lidandan on 2018/4/27.
 */

public class RegisterCourierActivity extends BaseActivity2 implements View.OnClickListener {
    private BroadcastReceiver smsReceiver;
    private IntentFilter smsFilter;

    private TextView mRegisterGetCodeTV;
    private DeleteEditText mRegisterCodeEdit;
    private TextView mRegisterTV;
    private DeleteEditText mRegisterPhoneEdit;
    private int clickCount = 1;

    private String phone;
    private String code;

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerSmsReceiver();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.register_courier);
        super.findViewById();
        getAppTitle().setCommonTitle("注册");
        mRegisterPhoneEdit = (DeleteEditText) findViewById(R.id.register_phone_edit);
        mRegisterCodeEdit = (DeleteEditText) findViewById(R.id.register_code_edit);
        mRegisterGetCodeTV = (TextView) findViewById(R.id.register_get_code);
        mRegisterGetCodeTV.setOnClickListener(this);
        mRegisterTV = (TextView) findViewById(R.id.register_tv);
        mRegisterTV.setOnClickListener(this);
        TextView mUserAgreementTv = (TextView) findViewById(R.id.user_agreement_tv);
        mUserAgreementTv.setOnClickListener(this);

        mRegisterPhoneEdit.addTextChangedListener(new droid.frame.view.TextWatcherExt(1) {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 可以修改手机号, 但是必须等到30s以后才可以重新发送
                if (s.length() == 13 && recLen == 30) {
                    mRegisterGetCodeTV.setEnabled(true);
                    mRegisterGetCodeTV.setBackgroundResource(R.drawable.app_courier_press_shape);
                    if (mRegisterCodeEdit.getText().length() >= 4) {
                        mRegisterTV.setEnabled(true);
                    } else {
                        mRegisterTV.setEnabled(false);
                    }
                } else {
                    mRegisterTV.setEnabled(false);
                    mRegisterGetCodeTV.setEnabled(false);
                }
            }
        });
        mRegisterCodeEdit.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() >= 4) {
                    if (mRegisterPhoneEdit.getText().length() == 13) {
                        mRegisterTV.setEnabled(true);
                    } else {
                        mRegisterTV.setEnabled(false);
                    }
                } else {
                    mRegisterTV.setEnabled(false);
                }
                // 输入完寄件码，自动验证
                if (s.length() == 4) {
                    loginVerify();
                }
            }
        });
        SpannableString spannableString = new SpannableString("注册即表示已阅读并用以《火箭侠用户协议》");
        UnderlineSpan underlineSpan = new UnderlineSpan();
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#007aff"));
        spannableString.setSpan(colorSpan, 11, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(underlineSpan, 11, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mUserAgreementTv.setText(spannableString);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private int recLen = 30;
    private boolean isStart;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (recLen == 1) {
                isStart = false;
                recLen = 30;
                mRegisterGetCodeTV.setEnabled(true);
                mRegisterGetCodeTV.getPaint().setFlags(0);
                mRegisterGetCodeTV.setText("重新获取");
            }
            if (recLen == 29) {
                clickCount++;
                showToast("短信验证码已发送");
            }
            if (isStart) {
                recLen--;
                mRegisterGetCodeTV.setEnabled(false);
                mRegisterGetCodeTV.getPaint().setFlags(0);
                mRegisterGetCodeTV.setBackgroundResource(R.drawable.app_courier_press_shape);
                mRegisterGetCodeTV.setText(recLen + "秒后重新发送");
                getHandler().postDelayed(this, 1000);
            }
        }
    };

    /**
     * 登录验证
     */
    private void loginVerify() {
        phone = mRegisterPhoneEdit.getText().toString().replace(" ", "");
        code = mRegisterCodeEdit.getText().toString();
        if (Str.isEmpty(phone)) {
            showToast("请输入手机号，获取验证码");
            return;
        }
        showLoadingDialog(null);
        AppHttp.getInstance().courierLoginVerifyCode(phone, code, 1);
    }

    private void countDownStart() {
        getHandler().postDelayed(runnable, 1000);
        isStart = true;
        mRegisterGetCodeTV.setEnabled(false);
        mRegisterCodeEdit.requestFocus();
        InputMethodManager imm = (InputMethodManager) mRegisterCodeEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    public Handler smsHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                mRegisterCodeEdit.setText(msg.obj.toString());
            }
        }
    };

    private void registerSmsReceiver() {
        smsFilter = new IntentFilter();
        smsFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        smsFilter.setPriority(Integer.MAX_VALUE);
        smsReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Object[] objs = (Object[]) intent.getExtras().get("pdus");
                for (Object obj : objs) {
                    byte[] pdu = (byte[]) obj;
                    SmsMessage sms = SmsMessage.createFromPdu(pdu);
                    String message = sms.getMessageBody();
                    String from = sms.getOriginatingAddress();
                    if (!TextUtils.isEmpty(from)) {
                        String code = patternCode(message);
                        if (!TextUtils.isEmpty(code)) {
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = code;
                            smsHandler.sendMessage(msg);
                        }
                    }
                }
            }
        };
        registerReceiver(smsReceiver, smsFilter);
    }

    /**
     * @Title: 匹配短信中间的6个数字（验证码等）
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile("(?<!\\d)\\d{4}(?!\\d)");
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 注册
            case R.id.register_tv:
                loginVerify();
                break;
            //获取验证码
            case R.id.register_get_code:
                if (mRegisterPhoneEdit.getText().length() == 13) {
                    phone = mRegisterPhoneEdit.getText().toString().replace(" ", "");
                    showLoadingDialog(null);
                    if (clickCount > 2) {
                        AppHttp.getInstance().courierGetSMSVerifyCode(phone, "1");
                    } else {
                        AppHttp.getInstance().courierGetSMSVerifyCode(phone, "");
                    }
                } else {
                    showToast("手机号输入有误");
                }
                break;
            default:
                break;
        }
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 发送验证码
            case MsgID.courier_send_verifyNum:
                cancelLoadingDialog();
                ReqResult<?> result = JSON.parser(msg.obj);
                if (checkLoginStatus(result)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            countDownStart();
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return false;
            // 确认验证码,并注册
            case MsgID.courier_login_verify_code + 1:
                cancelLoadingDialog();
                final ReqResult<UserBean> result1 = JSON.parser(msg.obj, UserBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AppCache.setUser(null);
                        AppCache.setOrder(null);
                        AppCache.setStationOpenInfoBean(null);
                        if (checkLoginStatus(result1)) {
                            UserBean user = result1.getResult();
                            if (user != null) {
                                if (isEmpty(user.getPhone())) {
                                    user.setPhone(phone);
                                }
                                user.setIsJam(1);
                                AppCache.setUser(user);
                                if (user.getState() == Const.CourierRegisterStatus.RegisterOkStatus) {
                                    showToast("您已经是火箭侠了哦！");
                                    AppLogic.onPaySuccess(getContext());
                                } else {
                                    Intent intent = new Intent();
                                    intent.setClass(RegisterCourierActivity.this, RegisterCourierStepActivity.class);
                                    startActivity(intent);
                                    setResult(Activity.RESULT_OK);
                                }
                                finish();
                            }
                        } else {
                            showToast(result1.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (smsReceiver != null) {
            unregisterReceiver(smsReceiver);
        }
        if (runnable != null) {
            getHandler().removeCallbacks(runnable);
        }
    }
}


